package com.hualan.sfzy.service.impl;


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hualan.sfzy.constant.CommonConstant;
import com.hualan.sfzy.mapper.FmClassifyMapper;
import com.hualan.sfzy.mapper.FmMapper;
import com.hualan.sfzy.model.entity.FmClassify;
import com.hualan.sfzy.model.vo.FmQuery;
import com.hualan.sfzy.service.FmClassifyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * FM分类服务实现类
 */
@Service
public class FmClassifyServiceImpl implements FmClassifyService {
    @Autowired
    private FmClassifyMapper fmClassifyMapper;
    @Autowired
    private FmMapper fmMapper;

    @Override
    public int add(FmClassify entity) {
        return fmClassifyMapper.insert(entity);
    }

    @Override
    public int edit(FmClassify entity) {
        return fmClassifyMapper.update(entity);
    }

    @Override
    public int remove(Integer id) {
        // 创建查询对象
        FmQuery query = new FmQuery();
        // 设置查询条件为当前分类ID
        query.setFmId(id);

        // 查询该分类下的关联数据数量
        int count = fmMapper.select(query).size();

        // 如果存在关联数据，抛出异常阻止删除
        if (count > 0) {
            throw new RuntimeException("该分类下有关联内容，请先删除关联内容");
        }
        return fmClassifyMapper.delete(id);
    }

    @Override
    public int removeBatch(Integer[] ids) {
        // 遍历每个要删除的分类ID
        for (Integer id : ids) {
            // 创建查询对象
            FmQuery query = new FmQuery();
            // 设置查询条件为当前分类ID
            query.setFmId(id);

            // 查询该分类下的关联数据数量
            int count = fmMapper.select(query).size();

            // 如果存在关联数据，抛出异常阻止删除
            if (count > 0) {
                throw new RuntimeException("ID为" + id + "的分类下有关联内容，请先删除关联内容");
            }
        }
        return fmClassifyMapper.deleteBatch(ids);
    }

    @Override
    public List<FmClassify> find() {
        return fmClassifyMapper.select(new FmClassify());
    }

    @Override
    public Map<String, Object> findPage(Integer pageNum, Integer pageSize, FmClassify entity) {
        PageHelper.startPage(pageNum, pageSize);
        List<FmClassify> list = fmClassifyMapper.select(entity);
        PageInfo<FmClassify> pageInfo = new PageInfo<>(list);
        Map<String, Object> pageMap = new HashMap<>();
        pageMap.put(CommonConstant.PAGE_LIST, list);
        pageMap.put(CommonConstant.PAGE_TOTAL, pageInfo.getPages());
        pageMap.put(CommonConstant.TOTAL, pageInfo.getTotal());
        return pageMap;
    }

    @Override
    public FmClassify findById(Integer id) {
        return fmClassifyMapper.selectById(id);
    }
}